package m202406.d09;

import java.util.Arrays;
import java.util.Stack;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/6/9 13:29
 */
public class Q32 {

    public static void main(String[] args) {
        Q32 q32 = new Q32();
        q32.longestValidParentheses("))()()()");
    }

    public int longestValidParentheses(String s) {
        int[] flag = new int[s.length()];
        convert(s, flag);
        int max = 0;
        int count = 0;
        for (int i : flag) {
            if (i != 1) {
                max = Math.max(max, count);
                count = 0;
            } else {
                count++;
            }
        }
        return Math.max(max, count);
    }

    private void convert(String s, int[] flag) {
        Stack<Node> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                stack.push(new Node(c, i));
            } else {
                if (stack.isEmpty()) {
                    continue;
                }
                Node pop = stack.pop();
                //栈种只会放入(,所以栈不为空时出栈的一定就是'(',那么与当前')'就可以匹配
                flag[i] = 1;
                flag[pop.index] = 1;
            }
        }
    }


    private static class Node {
        char c;
        int index;

        public Node(char c, int index) {
            this.c = c;
            this.index = index;
        }
    }
}
